package com.share.tools;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import org.apache.commons.io.IOUtils;
import org.yaml.snakeyaml.Yaml;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author caifan
 * @since 2022/8/31
 */
public class YamlUtils {

    /**
     * json字符串转yaml
     * @param json
     * @return
     * @throws Exception
     */
    public static String json2Yaml(String json) throws Exception {
        final JsonNode jsonNode = new ObjectMapper().readTree(json);
        String yaml = new YAMLMapper().writeValueAsString(jsonNode);
        return yaml.replace("---", "");
    }

    /**
     * yaml转json
     * @param yamlStr yaml字符串
     * @return json
     * @throws Exception
     */
    public static String yaml2Json(String yamlStr) throws Exception {
        ObjectMapper om = new ObjectMapper();
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        final Object obj = objectMapper.readValue(yamlStr, Object.class);
        return om.writeValueAsString(obj);
    }

    public static List<String> yaml2Jsonarray(String yamlStr) throws Exception {
        Yaml yaml = new Yaml();
        Iterable<Object> ret = yaml.loadAll(yamlStr);
        List<String> strList = new ArrayList<>();
        for (Object o : ret) {
            strList.add(o.toString());
        }
        return strList;
    }

    public static void main(String[] args) throws Exception {
        String multiYaml = IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream("application.yaml"), Charset.defaultCharset());
        System.out.println(yaml2Jsonarray(multiYaml));
    }



}
